#!/usr/bin/env python3
"""
启动脚本 - 同时启动后端API服务器和MCP WebSocket服务器

这个脚本会同时启动：
1. FastAPI后端服务器（端口8001）
2. MCP WebSocket服务器（端口8080）

使用方法：
python start_servers.py

作者: 张朝文
版本: 1.0.0
"""

import asyncio
import subprocess
import threading
import signal
import sys
import time
import os
from pathlib import Path

def run_backend_server():
    """运行后端API服务器"""
    try:
        print("启动FastAPI后端服务器...")
        subprocess.run([
            sys.executable, "-m", "uvicorn", 
            "app.main:app",
            "--host", "127.0.0.1",
            "--port", "8001",
            "--reload",
            "--log-level", "info"
        ], check=True)
    except subprocess.CalledProcessError as e:
        print(f"后端服务器启动失败: {e}")
    except KeyboardInterrupt:
        print("后端服务器已停止")

def run_mcp_server():
    """运行MCP WebSocket服务器"""
    try:
        print("启动MCP WebSocket服务器...")
        subprocess.run([sys.executable, "mcp_server_simple.py"], check=True)
    except subprocess.CalledProcessError as e:
        print(f"MCP服务器启动失败: {e}")
    except KeyboardInterrupt:
        print("MCP服务器已停止")

def signal_handler(signum, frame):
    """信号处理器"""
    print(f"\n收到信号 {signum}，正在停止所有服务器...")
    sys.exit(0)

def main():
    """主函数"""
    # 注册信号处理器
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    print("=" * 60)
    print("大模型集成对话系统 - 服务器启动")
    print("=" * 60)
    print("将启动以下服务：")
    print("1. FastAPI后端服务器 - http://127.0.0.1:8001")
    print("2. MCP WebSocket服务器 - ws://localhost:8080/mcp")
    print("=" * 60)
    
    try:
        # 启动MCP服务器线程
        mcp_thread = threading.Thread(target=run_mcp_server, daemon=True)
        mcp_thread.start()
        
        # 等待MCP服务器启动
        print("等待MCP服务器启动...")
        time.sleep(3)
        
        # 在主线程中运行后端服务器
        print("启动后端API服务器...")
        run_backend_server()
        
    except KeyboardInterrupt:
        print("\n收到中断信号，正在停止所有服务器...")
    except Exception as e:
        print(f"启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
